package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//@WebFilter("/*")//拦截所有的请求
@Slf4j
public class CheckLoginFilterDemo implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将ServletRequest强制准换为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求的url并判断是否包含login
        String url = request.getRequestURL().toString();
        if(url.contains("login")){
            filterChain.doFilter(request,response);//放行
            return;
        }
        //2.获取请求是否带有token，如果没有返回错误
        String token = request.getHeader("token");
        log.info("请求的令牌：{}",token);
        if(!StringUtils.hasLength(token)){
            log.info("没有令牌");
            Result result = Result.error("NOT_LOGIN");
            //将Result类型的数据转换为json格式
            String json = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            //响应数据
            response.getWriter().write(json);
            return;
        }
        //3.解析token，如果解析错误返回错误
        try {
            JwtUtils.parseJWT(token);
        }catch(Exception e){
            log.info("令牌解析错误");
            Result result = Result.error("NOT_LOGIN");
            //将Result类型的数据转换为json格式
            String json = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            //响应数据
            response.getWriter().write(json);
            return;
        }

        //4.放行
        filterChain.doFilter(request,response);
    }
}
